package edu.columbia.aicheckers.agent;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Set;

import edu.columbia.aicheckers.model.Checker;
import edu.columbia.aicheckers.model.Color;
import edu.columbia.aicheckers.model.IBoardState;
import edu.columbia.aicheckers.model.Move;

/**
 * An agent that allows a human player to interact by making move decisions
 * @author Marshall
 *
 */
public class ConsoleAgent implements IAgent{

	StringBuilder sb = new StringBuilder();
	BufferedReader inputStream = new BufferedReader(new InputStreamReader(System.in));
	
	public ConsoleAgent()
	{
		for(int i = 0;i < 8; i ++)
		{
			sbToString[i] = new StringBuilder();
		}
	}
	
	public Move doPly(IBoardState board, Color myColor) {
		
		
		Set<Move> moves = board.getAvailableMoves(myColor);
		if(moves.isEmpty())
		{
			System.out.println("No more moves left...");
			return null;
		}
		System.out.println("Current board state - (You are " + myColor.name() + "):");
		System.out.println(board.toString());
		Move[] moveArray = new Move[moves.size()];
		int count = 0;
		sb.setLength(0);
		for(Move m : moves)
		{
			moveArray[count++] = m;
		}
		System.out.println(getStringMovesAndState(board,moves));
		System.out.println("Chooose a move:");
		try {
			while(true)
			{
				String line = inputStream.readLine();
				try
				{
					int moveNumber = Integer.parseInt(line);
					if(moveNumber < 0 || moveNumber >= moveArray.length)
					{
						System.err.println("Please input a valid number [0 - " + moveArray.length + "]");
						continue;
					}
					return moveArray[moveNumber];
				}
				catch(NumberFormatException n)
				{
					System.err.println("Please input a valid number (integer)");
				}
				
				
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	
	}
	
	StringBuilder[] sbToString = new StringBuilder[8];

	StringBuilder sb2 = new StringBuilder();
	private void clearStringBuilders()
	{
		for(int i = 0;i < 8; i++)
		{
			sbToString[i].setLength(0);
		}
	}
	
	public String getStringMovesAndState(IBoardState state, Set<Move> moves)
	{
		clearStringBuilders();
		int count = 0;
		for(Move m: moves)
		{
			IBoardState next = state.simulateMove(m);
			String nextString = next.toString();
			String[] rows = nextString.split("\n");
			for(int i = 0;i < 8; i ++)
			{
				if(i == 0)
				{
					sbToString[i].append(count++);
					sbToString[i].append(". ");
				}
				else
				{
					sbToString[i].append("   ");
				}
				sbToString[i].append(rows[i]);
				
			}
		}
		sb2.setLength(0);
		for(int i = 0;i < 8; i ++)
		{
			sb2.append(sbToString[i].toString());
			sb2.append("\n");
		}
		return sb2.toString();
	}
}
